package com.ruoyi.file.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.ruoyi.file.config.TencentCloudProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@Service
public class TencentCosSysFileServiceImpl implements ISysFileService{

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    //获取cosclient
    public COSClient getCosClient(){
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = tencentCloudProperties.getSecretId();
        String secretKey = tencentCloudProperties.getSecretKey();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        //获取cosclient
        COSClient cosClient = this.getCosClient();
        //文件上传
        //元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());
        //向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件后缀名
        String uploadPath = "/meeting/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
        // 01.jpg ->  /meeting/0o98754.jpg
        PutObjectRequest putObjectRequest = null;
        try {
            //设置bucket名称
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
                    uploadPath,
                    file.getInputStream(),
                    meta);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard);
        cosClient.putObject(putObjectRequest);    //上传文件
        String url = "https://" + tencentCloudProperties.getBucketPrivate() + ".cos." + tencentCloudProperties.getRegion() + ".myqcloud.com" + uploadPath;
        return url;


//        //封装请求对象：GeneratePresignedUrlRequest
//        GeneratePresignedUrlRequest request =
//                new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, HttpMethodName.GET);
//        //调用方法获取url
//        URL url = cosClient.generatePresignedUrl(request);
//        cosClient.shutdown();
//        return url.toString();
    }
}
